package com.best.onegous.Rewrite;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.best.onegous.R;
import com.best.onegous.agreement.ApiInterface;
import com.best.onegous.agreement.Apps;
import com.best.onegous.agreement.Common;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * ViewPager实现的轮播图广告自定义视图，如京东首页的广告轮播图效果； 既支持自动轮播页面也支持手势滑动切换页面
 * 
 * 
 */

public class SlideShowView extends FrameLayout {

	private Context context;
	private View bannerView;
	private ChildViewPager bannerViewPager;
	private ImageView[] imageViews = null;
	private ImageView imageView = null;
	private AtomicInteger what = new AtomicInteger(0);
	private boolean isContinue = true;
	private TimerTask task;
	private int page = 0;

	public SlideShowView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public SlideShowView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;

		initUI(context);

	}

	/**
	 * 初始化Views等UI
	 */
	private void initUI(Context context) {

		bannerView = LayoutInflater.from(context).inflate(
				R.layout.layout_slideshow, this, true);
		bannerViewPager = (ChildViewPager) bannerView
				.findViewById(R.id.banner_viewpager);
		// gundongimg();

	}

	public void gundongimg(JSONArray rows) throws JSONException {
		LinearLayout group = (LinearLayout) bannerView
				.findViewById(R.id.indicatorLayout);
		// 这里存放的是四张广告背景
		List<View> advPics = new ArrayList<View>();
		for (int i = 0; i < rows.length(); i++) {
			JSONObject s = rows.getJSONObject(i);
			ImageView img1 = new ImageView(context);
			img1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));
			img1.setScaleType(ImageView.ScaleType.FIT_XY);
			Apps.imageLoader.displayImage(
					Common.PHOTOURL+s.getString("src"),
					img1, Apps.allimg);
			advPics.add(img1);
		}
		// 对imageviews进行填充
		imageViews = new ImageView[advPics.size()];
		// 小图
		group.removeAllViews();
		for (int i = 0; i < advPics.size(); i++) {
			imageView = new ImageView(context);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(10, 10);

			lp.setMargins(0, 0, 8, 0);
			imageView.setLayoutParams(lp);
			imageViews[i] = imageView;
			if (i == 0) {
				imageViews[i].setBackgroundResource(R.drawable.yuan1);
			} else {
				imageViews[i].setBackgroundResource(R.drawable.yuan2);
			}
			group.addView(imageViews[i]);
		}
		bannerViewPager.setAdapter(new AdvAdapter(advPics));
		bannerViewPager.setOnPageChangeListener(new GuidePageChangeListener());
		bannerViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});
		autogallery();
	}

	private void autogallery() {
		Timer time = new Timer();
		task = new TimerTask() {
			@Override
			public void run() {
				Message m = new Message();
				// handler_gallery.sendMessage(m);
				if (isContinue) {
					viewHandler.sendMessage(m);
				}
			}
		};
		time.schedule(task, 5000, 5000);
	}

	private final Handler viewHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (page < 4) {
				page++;
			} else {
				page = 0;
			}
			bannerViewPager.setCurrentItem(page, true);
			super.handleMessage(msg);
		}
	};

	private final class GuidePageChangeListener implements OnPageChangeListener {
		boolean isAutoPlay = false;

		@Override
		public void onPageScrollStateChanged(int arg0) {

			switch (arg0) {
			case 1:// 手势滑动，空闲中
				isAutoPlay = false;
				break;
			case 2:// 界面切换�?
				isAutoPlay = true;
				break;
			case 0:// 滑动结束，即切换完毕或�?�加载完�?
					// 当前为最后一张，此时从右向左滑，则切换到第一�?
				if (bannerViewPager.getCurrentItem() == bannerViewPager
						.getAdapter().getCount() - 1 && !isAutoPlay) {
					bannerViewPager.setCurrentItem(0);
					page = 0;
				}
				// 当前为第�?张，此时从左向右滑，则切换到�?后一�?
				else if (bannerViewPager.getCurrentItem() == 0 && !isAutoPlay) {
					page = 3;
					bannerViewPager.setCurrentItem(bannerViewPager.getAdapter()
							.getCount() - 1);
				}
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			what.getAndSet(arg0);
			for (int i = 0; i < imageViews.length; i++) {
				imageViews[arg0].setBackgroundResource(R.drawable.yuan1);
				if (arg0 != i) {
					imageViews[i].setBackgroundResource(R.drawable.yuan2);
				}
			}
		}
	}

	private final class AdvAdapter extends PagerAdapter {
		private List<View> views = null;

		public AdvAdapter(List<View> views) {
			this.views = views;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(views.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public Object instantiateItem(View arg0, final int arg1) {
			((ViewPager) arg0).addView(views.get(arg1), 0);
			/*
			 * views.get(arg1).setOnClickListener(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { // TODO Auto-generated
			 * method stub String[] item = mString.get(arg1); intent = new
			 * Intent(getActivity(),TieZiXiangQing.class); intent.putExtra("id",
			 * item[1]); getActivity().startActivity(intent); } });
			 */

			return views.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

	}

}